package com.dewod.producesales.activity.setting;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.blankj.utilcode.util.ToastUtils;
import com.dewod.producesales.R;
import com.dewod.producesales.databinding.ActivityNetRequestSettingBinding;
import com.dewod.producesales.model.view.RequestSetting;
import com.dewod.producesales.service.RegisterService;
import com.dewod.producesales.viewmodel.NetSettingViewModel;

public class NetRequestSettingActivity extends AppCompatActivity {

    private RequestSetting requestSetting;

    private NetSettingViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_request_setting);

        // 初始化 ViewModel
        viewModel = new ViewModelProvider(this).get(NetSettingViewModel.class);
        // 加载本地存储的数据
        viewModel.loadSettings(this);

        // 绑定布局
        ActivityNetRequestSettingBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_net_request_setting);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this); // 让LiveData自动更新UI

        setupSaveAndResetButtons(binding);
        setupRadioGroup(binding.radioGroup);
        dataListening();
    }

    private void dataListening(){
        viewModel.schema.observe(this, this::updateRadioGroupSelection);
    }

    private void updateRadioGroupSelection(String targetSchema) {
        RadioGroup radioGroup = findViewById(R.id.radioGroup);

        int childCount = radioGroup.getChildCount();

        for (int i = 0; i < childCount; i++) {
            View child = radioGroup.getChildAt(i);
            if (child instanceof RadioButton) {
                RadioButton radioButton = (RadioButton) child;
                if (radioButton.getText().toString().equals(targetSchema)) {
                    radioButton.setChecked(true);
                    return;
                }
            }
        }
    }

    @SuppressLint("ResourceType")
    private void setupRadioGroup(RadioGroup radioGroup) {
        final String[] items = getResources().getStringArray(R.array.schema);
        for (String item : items) {
            RadioButton button = new RadioButton(this);
            button.setId(View.generateViewId());
            button.setText(item);
            button.setChecked(item.equals(viewModel.schema.getValue()));
            button.setButtonTintList(ContextCompat.getColorStateList(this, R.drawable.radio_button_selector));
            radioGroup.addView(button);
        }

        radioGroup.setOnCheckedChangeListener((group1, checkedId) -> {
            RadioButton button = findViewById(checkedId);
            String schema = button.getText().toString();
            viewModel.updateSchema(schema);
        });
    }

    private void setupSaveAndResetButtons(ActivityNetRequestSettingBinding binding) {
        binding.btnSave.setOnClickListener(v -> {
            validateSettings();
        });

        binding.btnReset.setOnClickListener(v -> {
            RequestSetting defaultSetting = RequestSetting.init();
            viewModel.resetToDefault(defaultSetting);
            binding.setViewModel(viewModel); // 刷新UI绑定
        });
    }

    private void validateSettings(){
        String url = viewModel.getUrl();
        RegisterService.register(url, success -> {
            if (success) {
                // 注册成功逻辑
                viewModel.saveSettings(this);
                runOnUiThread(() -> Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show());
            } else {
                // 注册失败逻辑
                ToastUtils.showLong("地址请求失败，请检查修改后再保存");
            }
        });
    }





}
